const express = require('express')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const model = require('./model')
const Chat = model.getModel('chat')
const app = express()

const server = require('http').Server(app)

const io = require('socket.io')(server, { cors: true })

// 监听用户连接
io.on('connection', function(socket) {
  socket.on('sendmsg', function(data) {
    const { from, to, msg } = data
    // 每个聊天都有唯一的 id
    const chatid = [from, to].sort().join('_')
    Chat.create({chatid, from, to, content: msg}, function(err, doc) {
      // 广播（全局）事件
      io.emit('recvmsg', Object.assign({}, doc._doc))
    })
  })
})

const userRouter = require('./user')

app.use(cookieParser())
app.use(bodyParser.json())
app.use('/user', userRouter)
server.listen(9093, function() {
  console.log('server port is 9093')
})